/*
 * =====================================================================================
 *
 *       Filename:  queue.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  05/01/14 18:12:48
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Andy (gk), andy_y_li@163.com
 *        Company:  RD
 *
 * =====================================================================================
 */

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "queue.h"
#include <stdlib.h>

void createQueue(Queue *pq)
{
    memset(pq->data,0,MAX_QSIZE * sizeof(char));
    pq->front = pq->rear = 0;
    pq->len = 0;
}

int qIsFull(Queue *pq)
{
    return ((pq->rear + 1) % MAX_QSIZE == pq->front);
    //return pq->len == MAX_QSIZE;
}

int qIsEmpty(Queue *pq)
{
    return (pq->rear == pq->front);
    //return pq->len == 0;
}

int queue_length(Queue *pq)
{
    return pq->len;
}

int enItem(Queue *pq,const char *item)
{
    // Now, it store anyway
    /*
    if (qIsFull(pq)){
        return 0;
    }
    */
    int length = strlen(item) + 1;
   char *buf = (char*)malloc(length * sizeof(char));
    if (buf == NULL) {
        fprintf(stderr, "malloc error: %s\n", strerror(errno));
        return 0;
    }
    strncpy(buf, item, length * sizeof(char));
    pq->data[pq->rear] = buf;
    pq->rear = (pq->rear + 1) % MAX_QSIZE;
    pq->len++;
    return 1;
}

int deItem(Queue *pq,char *pitem, int max_len)
{
    if (qIsEmpty(pq)){
    return 0;
    }
    char *buf = pq->data[pq->front];
    int length = strlen(buf) + 1;
    length = (length > max_len?max_len:length);
    strncpy(pitem, buf, length * sizeof(char));
    pq->front = (pq->front + 1) % MAX_QSIZE;
    pq->len--;
    free(buf);
    return 1;
}


